﻿using System;
using System.Threading;

namespace Lucene.Linq.Utility
{
    internal static class ReaderWriterLockExtensions
    {
        public static IDisposable ReadLock(this ReaderWriterLock l)
        {
            l.AcquireReaderLock(-1);
            return new ActionDisposable(l.ReleaseReaderLock);
        }

        public static IDisposable ReadLock(this ReaderWriterLockSlim l)
        {
            l.EnterReadLock();
            return new ActionDisposable(l.ExitReadLock);
        }

        public static IDisposable UpgradableReadLock(this ReaderWriterLockSlim l)
        {
            l.EnterUpgradeableReadLock();
            return new ActionDisposable(l.ExitUpgradeableReadLock);
        }

        public static IDisposable WriteLock(this ReaderWriterLock l)
        {
            l.AcquireWriterLock(-1);
            return new ActionDisposable(l.ReleaseWriterLock);
        }

        public static IDisposable WriteLock(this ReaderWriterLockSlim l)
        {
            l.EnterWriteLock();
            return new ActionDisposable(l.ExitWriteLock);
        }
    }
}